<!--
 * @Description: 调度维护
 * @Author: fxg
 * @Date: 2020-06-29 11:18:28
 * @LastEditors: wangwangwang
 * @LastEditTime: 2021-04-14 16:32:37
-->
<template>
  <div class="pages_content table scheduling">
    <el-container>
      <el-header>
        <breaDcrumb />
      </el-header>
      <el-main>
        <div class="header_right" @click="showCardNav = !showCardNav">
          <div class="title">搜索</div>
          <div>
            <div :class="{ 'arrowTransform': !showCardNav, 'arrowTransformReturn': showCardNav}">
              <i style="margin-right: 5px" class="el-icon-arrow-down"></i>
            </div>
          </div>
        </div>
        <div v-show="showCardNav" class="hr"></div>
        <el-collapse-transition>
          <div v-show="showCardNav">
            <div class="search">
              <span style="display: inline-block;margin-bottom: 10px;">
                <span style="margin-right: 12px;">系统</span>
                <el-select v-model="tableParam.systemId" placeholder="请选择">
                  <el-option v-for="item in sysoptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
                </el-select>
              </span>
              <span style="margin-left: 24px;">
                <span style="margin-right: 12px;">接口名称</span>
                <el-input v-model="tableParam.name" style="width: 20%;max-width: 200px;" clearable placeholder="请输入"  @keyup.enter.native="queryPage()"/>
              </span>
              <el-button icon="el-icon-search" size="medium" class="bottom_all" @click="(tableParam.page = 1), queryPage()">查 询</el-button>
              <el-button size="medium" class="bottom_all_two" @click="reset()">重 置</el-button>
            </div>
          </div>
        </el-collapse-transition>
        <div class="hr"></div>
        <div class="card">
          <div class="card_nav">
            <div>
              <el-button v-if="ButtonList.findIndex(res=>(res.buttonValue=='TIANJIA'))!==-1" size="small" class="bottom_all" style="margin-left: 0;" @click="add()">
                <i class="icon iconfont iconicon_button_add" style="font-size: 12px;"></i>
                添加
              </el-button>
              <el-button v-if="ButtonList.findIndex(res=>(res.buttonValue=='SHANCHU'))!==-1" size="small" class="bottom_two" @click="batchUpdateOrDelete('update_status', 0)">
                <i class="icon iconfont iconicon_button_delete" style="font-size: 12px;"></i>
                删除
              </el-button>
              <el-button v-if="ButtonList.findIndex(res=>(res.buttonValue=='RIYONG'))!==-1" size="small" class="bottom_three" @click="batchUpdateOrDelete('update_enable', 1)">
                <i class="icon iconfont iconicon_button_startuse" style="font-size: 12px;"></i>
                启用
              </el-button>
              <el-button v-if="ButtonList.findIndex(res=>(res.buttonValue=='JINYONG'))!==-1" size="small" class="bottom_four" @click="batchUpdateOrDelete('update_enable', 0)">
                <i class="icon iconfont iconicon_button_disable1" style="font-size: 12px;"></i>
                禁用
              </el-button>
            </div>
            <div>
              <el-dropdown :hide-on-click="false" trigger="click" style="margin: 0 20px;">
                <el-link :underline="false">
                  <span class="el-icon--left">
                    <i class="iconfont iconicon_button_filtrate"></i>
                  </span>
                  筛选
                </el-link>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item v-for="(item, index) in table" :key="index">
                    <el-checkbox v-model="item.status">{{ item.label }}</el-checkbox>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
              <el-link v-if="ButtonList.findIndex(res=>(res.buttonValue=='DAOCHU'))!==-1" :underline="false" @click="$Download(DownloadURL, tableParam)">
                <span class="el-icon--left">
                  <i class="iconfont iconicon_button_export1"></i>
                </span>
                导出
              </el-link>
            </div>
          </div>
          <div class="card_info" :style="style">
            <el-table ref="multipleTable" :header-cell-style="{ background: '#f3f6f9' }" :cell-style="{ borderRight: 'none' }" border stripe style="width:100%" :data="tableData" tooltip-effect="dark" @selection-change="handleSelectionChange">
              <el-table-column align="center" type="selection" width="50"></el-table-column>
              <template v-for="(item, index) in table">
                <el-table-column v-if="item.status" :key="index" :label="item.label" align="center" :min-width="item.width" :fixed=" item.label =='操作'?'right':false">
                  <template slot-scope="scope">
                    <span v-if="scope.row.enable == 0 && item.label == '状态'" style="color:#969799;">禁用</span>
                    <span v-if="scope.row.enable == 1 && item.label == '状态'" style="color:#00A754;">启用</span>
                    <el-button v-if="item.label == '操作'&&ButtonList.findIndex(res=>(res.buttonValue=='CHAKRZ'))!==-1" class="bottom_one" size="mini" @click="detail(scope.row)">查看日志</el-button>
                    <el-button v-if="item.label == '操作'&&ButtonList.findIndex(res=>(res.buttonValue=='XIUGAI'))!==-1" class="bottom_one" size="mini" @click="update(scope.row)">
                      修改
                    </el-button>
                    <span v-if="item.label !== '操作' && item.label !== '状态'">{{ scope.row[item.prop] }}</span>
                  </template>
                </el-table-column>
              </template>
            </el-table>
          </div>
        </div>
      </el-main>
      <div class="card_bottom">
        <div class="card_bottom_left">
          <div class="top_page_totle">总共{{ total }}条</div>
          <el-pagination :current-page.sync="tableParam.page" :page-size="tableParam.pageSize" :page-sizes="[10, 20, 30, 40,50,100,200,500,1000]" layout="prev,pager,sizes,next,jumper" :total="total" @size-change="sizeChange" @current-change="queryPage()"></el-pagination>
        </div>
        <div>
          <el-button size="mini" class="bottom_all_two" icon="el-icon-refresh-right" @click="queryPage()">刷新</el-button>
        </div>
      </div>
    </el-container>
    <!-- 添加 -->
    <el-dialog v-dialogDrag :visible.sync="dialogVisible" width="560px" :before-close="resefrom" :close-on-click-modal="false">
      <span slot="title" class="dialog-title">{{ dialogtitle }}</span>
      <div class="dialoginfo">
        <el-form ref="dialogForm" :rules="rules" :inline="true" :model="from" label-width="90px">
          <el-form-item prop="name">
            <span slot="label" style="color:  #FF0000 ;">接口名称</span>
            <el-input v-model="from.name" placeholder="请输入" clearable></el-input>
          </el-form-item>
          <el-form-item prop="code">
            <span slot="label" style="color:  #FF0000 ;">编码</span>
            <el-input v-model="from.code" placeholder="请输入" clearable @input="changecode('code')"></el-input>
          </el-form-item>
          <el-form-item prop="apiTypeId">
            <span slot="label">接口类型</span>
            <el-select v-model="from.apiTypeId" placeholder="请选择">
              <el-option v-for="item in options" :key="item.id" :label="item.itemName" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="systemId">
            <span slot="label">所属系统</span>
            <el-select v-model="from.systemId" placeholder="请选择">
              <el-option v-for="item in sysoptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="time">
            <span slot="label">调度时间</span>
            <el-date-picker v-model="time" style="width: 340px;" type="datetimerange" unlink-panels range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
          </el-form-item>
          <el-form-item prop="scheduleInterval">
            <span slot="label">调度频率</span>
            <el-input v-model="from.scheduleInterval" style="width: 120px;" type="Number" placeholder="请填写时间" clearable />
            <el-select v-model="from.scheduleUnit" style="width: 100px; margin-left: 10px;" placeholder="请选择">
              <el-option
                v-for="item in speedOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
            <span style="padding-left: 10px;">一次</span>
          </el-form-item>
          <el-form-item label="状态" prop="enable">
            <el-radio-group v-model="from.enable">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="接口地址" prop="apiUrl">
            <el-input v-model="from.apiUrl" placeholder="请填写接口地址" class="textarea" type="textarea" resize="none" rows="5"></el-input>
          </el-form-item>
          <el-form-item label="系统描述" prop="description">
            <el-input v-model="from.description" placeholder="请填写系统描述" class="textarea" type="textarea" resize="none" rows="5"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="bottom_all_two" @click="resefrom()">取 消</el-button>
        <el-button class="bottom_all" :loading="loading" @click="save()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 查看日志 -->
    <el-dialog v-dialogDrag :visible.sync="dialog1" width="880px" :close-on-click-modal="false">
      <span slot="title" class="dialog-title">查看日志</span>
      <div>
        <el-table :header-cell-style="{ background: '#f3f6f9' }" :cell-style="{ borderRight: 'none' }" border stripe style="width: 100%" :data="dialoData" tooltip-effect="dark">
          <el-table-column align="center" label="接口" prop="apiUrl"></el-table-column>
          <el-table-column align="center" label="调度开始时间" prop="startTime"></el-table-column>
          <el-table-column align="center" label="调度结束时间" prop="endTime"></el-table-column>
        </el-table>
        <div class="pagination">
          <div class="top_page_totle">总共{{ dialototal1 }}条</div>
          <el-pagination :current-page.sync="dialogParam.page" :page-size="dialogParam.pageSize" layout="prev, pager, next, jumper" :total="dialototal1" @current-change="getdialoData()"></el-pagination>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="bottom_all_two" @click="dialog1=false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import breaDcrumb from "@/components/breadcrumb";
import { mapGetters } from "vuex";
import {
  queryPage,
  saveOrUpdate,
  batchUpdateOrDelete,
  get_schedule_logs, Download,
} from "@/api/basedata/scheduling.js";
import { getDicType } from "@/api/common.js";
import { queryPage as querybusinessPage } from "@/api/basedata/business.js";
import {
  codeReg, sortReg
} from "@/common/RegExp.js";
export default {
  components: {
    breaDcrumb,
  },
  data() {
    var validatePass1 = (rule, value, callback) => {
      if (sortReg(value)) {
        callback();
      } else {
        callback(new Error("请输正整数序号!"));
      }
    };
    return {
      DownloadURL: Download,
      /*添加修改弹窗*/
      dialogVisible: false,
      dialogtitle: "添加",
      options: [],
      sysoptions: [],
      /*弹要修改过着添加的数据*/
      from: {
        name: "",
        apiTypeId: "",
        apiUrl: "",
        systemId: "",
        description: "",
        enable: 1,
        code: "",
        scheduleUnit: 'unit_second', // 调度时间间隔单位默认秒
      },
      /*判断收起展开*/
      showCardNav: true,
      /*搜索关键字段*/
      /*列表展示*/
      rules: {
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
        code: [{ required: true, message: "请输入编码", trigger: "blur" }],
        apiTypeId: [
          { required: true, message: "请选择接口类型", trigger: "change" },
        ],
        systemId: [
          { required: true, message: "请选择系统", trigger: "change" },
        ],
        scheduleInterval: [
          { required: true, message: "请输入调度频率", trigger: "blur" },
          { validator: validatePass1, trigger: "blur", }
        ],
        apiUrl: [{ required: true, message: "请输接口地址", trigger: "blur" }],
      },
      table: [
        { label: "编码", width: "120", prop: "code", status: true },
        { label: "接口名称", width: "160", prop: "name", status: true },
        { label: "接口类型", width: "120", prop: "apiTypeName", status: true },
        { label: "接口地址", width: "220", prop: "apiUrl", status: true },
        { label: "所属系统", width: "120", prop: "systemName", status: true },
        { label: "调度时间", width: "160", prop: "createTime", status: true },
        { label: "描述", width: "280", prop: "description", status: true },
        { label: "状态", width: "120", prop: "enable", status: true },
        { label: "操作", width: "220", prop: "", status: true },
      ],
      /*列表选中的数据集*/
      tableParam: {
        page: 1,
        pageSize: 10,
        code: "",
        systemId: "",
      },
      time: [],
      total: 0,
      ids: [],
      sortIds: [],
      tableData: [],
      ButtonList: [],
      dialog1: false,
      dialototal1: 0,
      dialogParam: {
        page: 1,
        pageSize: 10,
      },
      dialoData: [],
      loading: false,
      speedOptions:[
        { label: '年', value: 'unit_year' },
        { label: '季度', value: 'unit_quarter' },
        { label: '月', value: 'unit_month' },
        { label: '周', value: 'unit_week' },
        { label: '天', value: 'unit_day' },
        { label: '小时', value: 'unit_hour' },
        { label: '分钟', value: 'unit_minute' },
        { label: '秒', value: 'unit_second' },
      ]
    };
  },
  beforeCreate() {
    getDicType({ code: "attachment" }).then((res) => {
      this.options = res.data.items;
    });
    let params = {
      page: 1,
      pageSize: 10000000,
    };
    querybusinessPage(params).then((res) => {
      this.sysoptions = res.data.data;
    });
  },
  mounted() {
    this.ButtonList = this.$ButtonList()
    this.queryPage();
  },
  methods: {
    changecode(key) {
      this.from[key] = codeReg(this.from[key]);
    },
    detail(low) {
      this.dialogParam.scheduleManagerId = low.id
      this.getdialoData()
    },
    async getdialoData() {
      const { data } = await get_schedule_logs(this.dialogParam)
      this.dialototal1 = data.totalRows
      this.dialoData = data.data
      this.dialog1 = true
    },
    /*重置*/
    reset() {
      this.tableParam.code = "";
      this.tableParam.systemId = "";
      this.queryPage();
    },
    /*删除，禁用，启用，排序*/
    batchUpdateOrDelete(type, status) {
      console.log(this.ids);
      console.log(type);
      console.log(status);
      if (this.ids.length == 0) {
        this.$message({
          message: "请选择要操作的数据项",
          type: "warning",
        });
        return;
      }
      if (type === "update_status") {
        this.$confirm("此操作将永久删除该信息?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          cancelButtonClass: "bottom_all_two",
          confirmButtonClass: "bottom_all",
          type: "warning",
        })
          .then(() => {
            batchUpdateOrDelete({
              ids: this.ids,
              status: status,
              type: type,
            }).then(() => {
              this.reset();
            });
          })
          .catch(() => { });
      } else {
        batchUpdateOrDelete({
          ids: this.ids,
          status: status,
          type: type,
        }).then(() => {
          this.queryPage();
        });
      }
    },
    /*保存或修改*/
    save() {
      this.$refs.dialogForm.validate((valid) => {
        if (valid) {
          let object = {
            ...this.from,
            scheduleStartTime: new Date(this.time[0]).getTime(),
            scheduleEndTime: new Date(this.time[1]).getTime(),
          };
          this.loading = true;
          saveOrUpdate(object).then((res) => {
            if (res.code == 1001) {
              this.loading = false;
              this.$message({
                message: '保存成功！！！',
                type: 'success'
              });
              this.resefrom();
              this.queryPage();
            }

          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resefrom() {
      this.dialogVisible = false;
      this.time = "";
    },
    /*获取列表*/
    queryPage() {
      queryPage(this.tableParam).then((res) => {
        this.total = res.data.totalRows;
        this.tableData = res.data.data;
      });
    },
    add() {
      this.dialogtitle = "添加";
      this.$data.from = this.$options.data().from;
      setTimeout(() => {
        this.$refs.dialogForm.clearValidate();
      }, 10);
      this.dialogVisible = true;
    },
    update(data) {
      let str = JSON.stringify(data);
      this.from = JSON.parse(str);
      this.from.enable = Number(data.enable);
      this.from.scheduleUnit = this.from.scheduleUnit || 'unit_second';
      this.time = []
      this.time[0] = new Date(Number(data.scheduleStartTime)).Format('yyyy-MM-dd hh:mm:ss')
      this.time[1] = new Date(Number(data.scheduleEndTime)).Format('yyyy-MM-dd hh:mm:ss')
      this.dialogtitle = "修改";
      this.dialogVisible = true;
      setTimeout(() => {
        this.$refs.dialogForm.clearValidate();
      }, 10);
      str = null;
    },
    /*批量选择*/
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.ids = [];
      this.sortIds = [];
      val.forEach((item) => {
        this.ids.push(item.id);
        this.sortIds.push({ id: item.id, sortNum: item.sortNum });
      });
    },
    sizeChange(value) {
      this.tableParam.pageSize = value;
      this.queryPage();
    },
  },
  computed: {
    ...mapGetters({
      screenWidth: "getscreenWidth",
      screenHeight: "getscreenHeight",
      Collapse: "getsCollapse",
    }),
    style() {
      let num = 0;
      if (this.Collapse) {
        num = this.screenWidth - 124;
      } else {
        num = this.screenWidth - 220;
      }
      return "width:" + num + "px;";
    },
  },
};
</script>
<style lang="scss" scoped>
.scheduling {
  .table_link {
    margin: 0 10px;
    color: $bg_color;
  }

  .table_link:hover {
    opacity: 0.8;
  }
  .dialoginfo {
    .el-input,
    .el-select {
      width: 380px;
    }
    .textarea_input {
      padding-top: 10px;
      align-items: flex-start;
      height: 118px;
    }
    .textarea {
      width: 380px;
    }
  }
}
</style>
